//
//  MenuViewController.swift
//  MacStudy
//
//  Created by 30san on 2020/11/9.
//  Copyright © 2020 Dawninest. All rights reserved.
//

import Cocoa

class MenuViewController: NSViewController {

    private lazy var myItem: NSMenu = {
        // 代码添加item
        let myItem = NSMenu(title: "我的菜单")
        let menuItem = NSMenuItem(title: "第一个item", action: Selector(("clickMenuItem:")), keyEquivalent: "")
        let menuItem1 = NSMenuItem(title: "嵌套菜单", action: Selector(("clickMenuItem:")), keyEquivalent: "")
        
        // 添加嵌套菜单
        let subMenu = NSMenu(title: "子菜单")
        subMenu.addItem(withTitle: "第一个嵌套item", action: Selector(("clickMenuItem:")), keyEquivalent: "")
        
        menuItem1.submenu = subMenu
        
        myItem.addItem(menuItem)
        myItem.addItem(menuItem1)
        return myItem
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 获取app 默认应用菜单
        guard let menu = NSApp.menu else { return }
        for item in menu.items {
            let title = item.title
            print("title = \(title)")
        }
        
        
        
        
//        let view = NSView()
//        view.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
//        view.wantsLayer = true
//        view.layer?.backgroundColor = NSColor.red.cgColor
//        self.view.addSubview(view)
    }
    
    @objc func clickMenuItem(_ item: NSMenuItem) {
        print("clickMenuItem")
        item.state = item.state == NSControl.StateValue(rawValue: 0) ? NSControl.StateValue(rawValue: 1) : NSControl.StateValue(rawValue: 0)
    }
    
    override func rightMouseDown(with event: NSEvent) {
        super.rightMouseDown(with: event)
        NSMenu.popUpContextMenu(myItem, with: event, for: self.view)
    }
}
